<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
      .box {
         width: 100px;
         height: 100px;
         background: red;
         position: absolute;
         top: 0;
      }
      .left {
          left: 0;
      }
      .right {
          right: 0;
      }
    </style>
</head>
<body>
    <div id="div1" class="box left">
        div1
    </div>
    <div id="div2" class="box right">
        div2
    </div>
</body>
<script>
    // 普通拖拽
     class Drag{
         constructor(id){
             //  获取元素
             this.oDiv = document.querySelector(id)
             this.disX = 0;
             this.disY = 0;
             this.init();
         }
         init(){
            console.log(123);
             this.oDiv.onmousedown = (ev) => {
   
                this.disX = ev.clientX - this.oDiv.offsetLeft;
                this.disY = ev.clientY - this.oDiv.offsetTop;

                document.onmousemove = this.fnMove.bind(this);
                document.onmouseup = this.fnUp.bind(this);
                return false
             }
         }
         fnMove(ev){
             this.oDiv.style.left = ev.clientX - this.disX + 'px';
             this.oDiv.style.top = ev.clientY - this.disY + 'px';

         }
         fnUp(){
            document.onmousemove = null;
            document.onmouseup = null;
         }
     }
    //  子类 - 限制范围
    class LimitDrag extends Drag{
        fnMove(ev){
            super.fnMove(ev)
            // 限制范围
            if(this.oDiv.offsetLeft <= 0){
                this.oDiv.style.left = 0
            }
            if (this.oDiv.offsetTop < 0)  this.oDiv.style.top = 0; 
        }
    }
    // 调用
    new Drag('#div1')
    new LimitDrag('#div2')
</script>
</html>